<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\exception\BusinessException;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 应用配置管理
 *
 * @icon fa fa-circle-o
 */
class Appconfig extends Backend
{

    /**
     * Appconfig模型对象
     * @var \app\admin\model\Appconfig
     */
    protected $model = null;

    /**
     * c-config_value
     * @var string
     */
    private $inputId = 'c-config_value';

    /**
     * c-config_value
     * @var string
     */
    private $inputKey = 'config_value';

    /**
     * @var string
     */
    private $inputName = 'row[config_value]';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Appconfig;

    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->with('app')
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    if ($params['config_value_type'] == 'list') {
                        $params['config_value'] = $params['config_value'] ?: [];
                        $params['config_value'] = $this->formatListValue($params['config_value']);
                        $params['config_value'] = json_encode($params['config_value'], JSON_UNESCAPED_UNICODE);
                    }

                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign(
            'config_value_type_list', \app\admin\model\Appconfig::CONFIG_VALUE_TYPE_MAP
        );
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                //var_dump($params);
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }

                    // 如果是List
                    //var_dump($params);
                    if ($params['config_value_type'] == 'list') {
                        $params['config_value'] = $params['config_value'] ?: [];
                        $params['config_value'] = $this->formatListValue($params['config_value']);
                        $params['config_value'] = json_encode($params['config_value'], JSON_UNESCAPED_UNICODE);
                    }
                    //var_dump($params);

                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $this->view->assign("inputId", $this->inputId);
        $this->view->assign("inputName", $this->inputName);
        $this->view->assign("row", $row);
        $this->view->assign(
            'config_value_type_list', \app\admin\model\Appconfig::CONFIG_VALUE_TYPE_MAP
        );
        return $this->view->fetch();
    }

    private function formatListValue($config_value): array
    {
        $new_config_value = [];
        foreach ($config_value as $key => $val) {
            $new_config_value[] = $val;
        }
        return $new_config_value;
    }

    /**
     * @return void
     */
    public function buildAddConfigValueDom()
    {
        // 配置类型
        $config_type = $this->request->request('config_type', '');
        if (!$config_type) {
            $this->error('未选择配置类型');
        }

        // 匹配dom
        try {
            $dom = $this->buildConfigValueDom('', $config_type);
        } catch (\Exception $exception) {
            $this->error($exception->getMessage());
        }

        $this->success('success', null, $dom);
    }

    /**
     * buildEditConfigValueDom
     * @return void
     */
    public function buildEditConfigValueDom()
    {
        // 提取参数
        $config_id = $this->request->request('config_id', 0);
        $config_type = $this->request->request('config_type', '');
        if (!$config_id) {
            $this->error('未选择配置编号');
        }
        if (!$config_type) {
            $this->error('未选择配置类型');
        }

        // 查询配置
        $row = $this->model->find($config_id);
        if (!$row) {
            $this->error('配置信息不存在');
        }

        // 类型不一致清空值
        $config_value = $row['config_value'];
        if ($config_type != $row['config_value_type']) {
            $config_value = '';
        }

        // 匹配dom
        try {
            $dom = $this->buildConfigValueDom($config_value, $config_type);
        } catch (\Exception $exception) {
            $this->error($exception->getMessage());
        }

        $this->success('success', null, $dom);
    }

    /**
     * buildConfigValueDom
     * @param $config_value
     * @param $config_value_type
     * @return string
     */
    private function buildConfigValueDom($config_value, $config_value_type): string
    {
        // 设置表单id和name
        $inputId = $this->inputId;
        $inputKey = $this->inputKey;
        $inputName = $this->inputName;

        // 配置生成默认值
        $config_value = $config_value ?? '';
        $dom = '';
        switch ($config_value_type) {
            case 'string':
                $dom = '<input id="' . $inputId . '"  type="text" name="' . $inputName . '" value="' . $config_value . '"
                   class="form-control" data-rule="required"/>';
                break;
            case  'password':
                $dom = '<input id="' . $inputId . '"  type="password" name="' . $inputName . '" value="' . $config_value . '"
                   class="form-control" data-rule="required"/>';
                break;
            case  'text':
                $dom = '<textarea id="' . $inputId . '"  name="' . $inputName . '" class="form-control" data-rule="required" rows="5">' . $config_value . '</textarea>';
                break;
            case 'editor':
                $dom = '<textarea id="' . $inputId . '"  name="' . $inputName . '" class="form-control editor" data-rule="required" rows="5">' . $config_value . '</textarea>';
                break;
            case 'list':
                $dom = '<dl class="fieldlist" data-name="config_value" data-template="config_value_tpl">
                <dd>
                    <a href="javascript:;" class="btn btn-sm btn-success btn-append"><i class="fa fa-plus"></i>追加</a>
                </dd>
                <textarea name="config_value" class="form-control hide" cols="30"
                          rows="5">' . $config_value . '</textarea>
            </dl>
            <script type="text/html" id="config_value_tpl">
                <dd class="form-inline">
                    <input style="width: 418px;" type="text" name="row[<%=name%>][<%=index%>]"
                           class="form-control" value="<%=row%>" size="100">
                    <span class="btn btn-sm btn-danger btn-remove"><i class="fa fa-times"></i></span> <span
                        class="btn btn-sm btn-primary btn-dragsort"><i class="fa fa-arrows"></i></span>
                </dd>
            </script>';
                break;
            case 'image':
                $dom = '<div class="input-group">
                <input id="'.$inputId.'" data-rule="required" class="form-control" size="50"
                       name="'.$inputName.'" type="text" value="'.$config_value.'">
                <div class="input-group-addon no-border no-padding">
                    <span><button type="button" id="faupload-'.$inputKey.'" class="btn btn-danger faupload"
                                  data-input-id="c-'.$inputKey.'"
                                  data-mimetype="image/gif,image/jpeg,image/png,image/jpg,image/bmp,image/webp"
                                  data-multiple="false" data-preview-id="p-'.$inputKey.'"><i class="fa fa-upload"></i> 上传 </button></span>
                    <span><button type="button" id="fachoose-'.$inputKey.'" class="btn btn-primary fachoose"
                                  data-input-id="'.$inputId.'" data-mimetype="image/*" data-multiple="false"><i
                            class="fa fa-list"></i> 选择</button></span>
                </div>
                <span class="msg-box n-right" for="c-'.$inputKey.'"></span>
            </div>
            <ul class="row list-inline faupload-preview" id="p-'.$inputKey.'"></ul>';
                break;
            case 'map':
                $dom = '<dl class="fieldlist" data-name="{$inputName}">
                <dd>
                    <ins>键名</ins>
                    <ins>键值</ins>
                </dd>
                <dd>
                    <a href="javascript:;" class="btn btn-sm btn-success btn-append"><i class="fa fa-plus"></i> 追加</a>
                </dd>
                <textarea name="' . $inputName . '" class="form-control hide" cols="30" rows="5">' . $config_value . '</textarea>
            </dl>';
                break;
            case 'date':
                $dom = '<input id="' . $inputId . '"  type="text" name="' . $inputName . '" value="' . $config_value . '" class="form-control datetimepicker" data-date-format="YYYY-MM-DD" data-tip="" data-rule="required"/>';
                break;
            case 'time':
                $dom = '<input id="' . $inputId . '"  type="text" name="' . $inputName . '" value="' . $config_value . '" class="form-control datetimepicker" data-date-format="HH:mm:ss" data-tip="" data-rule="required"/>';
                break;
            case 'datetime':
                $dom = '<input id="' . $inputId . '"  type="text" name="' . $inputName . '" value="' . $config_value . '" class="form-control datetimepicker" data-date-format="YYYY-MM-DD HH:mm:ss" data-tip="" data-rule="required"/>';
                break;
            case 'datetime-range':
                $dom = '<input id="' . $inputId . '"  type="text" name="' . $inputName . '" value="' . $config_value . '" class="form-control datetimerange" data-date-format="YYYY-MM-DD HH:mm:ss" data-tip="" data-rule="required"/>';
                break;
            case 'number':
                $dom = '<input id="' . $inputId . '" type="number" name="' . $inputName . '" value="' . $config_value . '" class="form-control" data-tip="" data-rule="required"/>';
                break;
            case 'switch':
                $class = '';
                if (!$config_value) {
                    $class = 'fa-flip-horizontal text-gray';
                }
                $dom = '<input id="' . $inputId . '"  name="' . $inputName . '" data-tip="" type="hidden" value="' . $config_value . '">
            <a href="javascript:;" data-toggle="switcher" class="btn-switcher" data-input-id="' . $inputId . '"  data-yes="1"  data-no="0">
                <i class="fa fa-toggle-on text-success ' . $class . ' fa-2x"></i>
            </a>';
                break;
            default:
                throw new Exception('不支持的配置类型');
        }
        return $dom;
    }


}
